package com.azzcs.juc.stampedlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;

/**
 * @Author: wzg
 * @Date: 2021/6/21 上午9:52
 * 普通读写锁
 */
public class Main {
    private static volatile int num = 0;

    public static void main(String[] args) throws InterruptedException {
        StampedLock lock = new StampedLock();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                long stamp = lock.writeLock();
                try{
                    TimeUnit.MILLISECONDS.sleep(20);
                    num++;
                    System.out.println("write ... "+ num);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlockWrite(stamp);
                }
            }).start();
        }
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                long stamp = lock.readLock();
                try{
                    TimeUnit.MILLISECONDS.sleep(1000);
                    System.out.println("read ... "+ num);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlockRead(stamp);
                }
            }).start();
        }

        TimeUnit.SECONDS.sleep(3);
        System.out.println("main ...");
    }
}
